<?php

namespace App\Console\Commands\OpenShop;

use App\Library\Rms\RmsUserApi;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageModel;
use App\Models\OpenShop\InvestmentPromotion\OpenShopOrganizationManageUserModel;
use App\Remote\Rms\RmsUserRemote;
use GuzzleHttp\Exception\GuzzleException;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class RefreshSolicitBusiness extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'openShop:refresh-solicit-business';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '刷新招商人员信息';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     * @throws GuzzleException
     */
    public function handle()
    {
       $this->doHandle();
    }

    public function doHandle()
    {
        $rmsUserList = (new RmsUserApi())->getFsUsers('', ['*'], 'od-9b3d254f7b63605400a1f74c50586d3c')['data']['lists'] ?? [];
        $userLists   = array_column($rmsUserList, 'name', 'rmsUserId');
        $userIds     = array_keys($userLists);
        // 获取职位
        $roleId    = (new RmsUserApi())->roleIdsConfig()['data']['role']['province_develop_id'];
        $okUserIds = [];
        foreach ($userIds as $userId) {
            if (!$userId) {
                continue;
            }
            $isRoleUser = RmsUserRemote::isRoleUser($roleId, $userId)['isRoleUser'] ?? false;
            if ($isRoleUser) {
                $okUserIds[] = $userId;
            }
        }

        DB::beginTransaction();
        // 先删除
        OpenShopOrganizationManageUserModel::query()
                                           ->where('type', OpenShopOrganizationManageUserModel::TYPE_SOLICIT_BUSINESS)
                                           ->update(['isDeleted' => 1]);

        foreach ($okUserIds as $userId) {
            // 入库
            OpenShopOrganizationManageUserModel::query()->withoutGlobalScope('isDel')->updateOrCreate([
                'userId' => $userId,
                'type'   => OpenShopOrganizationManageUserModel::TYPE_SOLICIT_BUSINESS,
            ], [
                'name'      => $userLists[$userId]['username'] ?? '',
                'isDeleted' => 0,
            ]);
        }
        DB::commit();
    }
}
